package com.qingzhou.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.qingzhou.web.repository.dao.CollectDao;
import com.qingzhou.web.repository.dao.OmicsCollectDao;
import com.qingzhou.web.repository.dao.PatientDao;
import com.qingzhou.web.repository.entity.CollectEntity;
import com.qingzhou.web.repository.entity.OmicsCollectEntity;
import com.qingzhou.web.repository.entity.PatientEntity;
import com.qingzhou.web.repository.mapper.CollectMapper;
import com.qingzhou.web.repository.mapper.OmicsCollectMapper;
import com.qingzhou.web.service.*;
import com.qingzhou.web.service.impl.convert.MaterialsConverter;
import com.qingzhou.web.service.impl.convert.TestItemConverter;
import com.qingzhou.web.service.impl.params.request.*;
import com.qingzhou.web.service.impl.params.vo.CollectVo;
import com.qingzhou.web.service.impl.params.vo.OmicsCollectVo;
import com.qingzhou.web.service.util.DictUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Result;
import org.noear.solon.data.annotation.Tran;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class OmicsCollectServiceImpl extends ServiceImpl<OmicsCollectMapper, OmicsCollectEntity> implements OmicsCollectService {
    @Inject
    OmicsCollectDao omicsCollectDao;
    @Inject
    ConvertHelper convertHelper;
    @Inject
    DataCheckLogService dataCheckLogService;

    @Inject
    PatientDao patientDao;

    @Inject("${solon.url.khsystem}")
    String khSysUrl;

    @Override
    public int add(OmicsCollectAddForm form) {
        Assert.isTrue(StrUtil.isNotEmpty(form.getPatientCode()), "患者编号不允许为空");

        OmicsCollectEntity entity = BeanUtil.copyProperties(form, OmicsCollectEntity.class);
        entity.setStatus("create");
        return omicsCollectDao.add(entity);
    }

    @Override
    public int delete(OmicsCollectDeleteForm form) {
        OmicsCollectEntity entity = omicsCollectDao.getById(form.getId());
        Assert.isTrue(ObjUtil.isNotNull(entity), "数据不见了");
        Assert.isTrue(StrUtil.equalsIgnoreCase("create", entity.getStatus()), "该状态不允许删除");

        return omicsCollectDao.delete(form.getId());
    }

    @Override
    public Page<OmicsCollectVo> page(Page<OmicsCollectEntity> page, SubTablePageForm form) {
        QueryWrapper wrapper = QueryWrapper.create()
                .orderBy("create_time desc");
        List<String> patientCodeList = form.getPatientCodeList();
        String sampleNoStr = form.getSampleNoStr();
        if(CollUtil.isNotEmpty(patientCodeList)){
            wrapper.in("patient_code", form.getPatientCodeList());
        }
        if(StrUtil.isNotEmpty(sampleNoStr)){
            List<String> sampleNoList = StrUtil.split(sampleNoStr,"\n");
            List<String> likeConditions = new ArrayList<>();
            sampleNoList.forEach(item->{
                String conditionTpl = "sample_no like '%{}%'";
                likeConditions.add(StrUtil.format(conditionTpl,item));
            });
            if(CollUtil.isNotEmpty(likeConditions)){
                wrapper.and(CollUtil.join(likeConditions," or "));
            }
        }
        Page<OmicsCollectEntity> paginate = omicsCollectDao.getMapper().paginate(page, wrapper);
        return convertHelper.convertOmicsCollect(paginate);
    }

    @Override
    public OmicsCollectVo detail(OmicsCollectDetailForm form) {
        OmicsCollectEntity entity = omicsCollectDao.getById(form.getId());
        Assert.isTrue(ObjUtil.isNotNull(entity), "数据不见了");
        return convertHelper.convert(entity);
    }

    @Override
    public int edit(OmicsCollectEditForm form) {
        OmicsCollectEntity entity = omicsCollectDao.getById(form.getId());
        Assert.isTrue(ObjUtil.isNotNull(entity), "数据不见了");
        Assert.isTrue(StrUtil.equalsIgnoreCase("create", entity.getStatus()), "该状态不允许编辑");

        BeanUtil.copyProperties(form, entity,"patientCode"); //患者编号不能变
        return omicsCollectDao.update(entity);
    }

    @Override
    public int forceEdit(OmicsCollectForceEditForm form) {
        OmicsCollectEntity entity = omicsCollectDao.getById(form.getId());
        Assert.isTrue(ObjUtil.isNotNull(entity), "数据不见了");
        Assert.isTrue(StrUtil.equalsIgnoreCase("done", entity.getStatus()), "该状态不允许数据检查");

        JSONObject diffContent = DataCheckLogServiceImpl.diff(entity, form, new String[]{});
        BeanUtil.copyProperties(form, entity,"patientCode"); //患者编号不能变
        int rows = omicsCollectDao.update(entity);

        if (rows > 0 && MapUtil.isNotEmpty(diffContent)) {
            DataCheckLogAddForm addForm = new DataCheckLogAddForm(EdcConstants.EDC_OMICS_COLLECT, diffContent, entity.getPatientCode());
            dataCheckLogService.add(addForm);
        }

        return rows;
    }

    @Override
    @Tran
    public int done(OmicsCollectDoneForm form) {
        OmicsCollectEntity entity = omicsCollectDao.getById(form.getId());
        Assert.isTrue(ObjUtil.isNotNull(entity), "数据不见了");
        Assert.isTrue(StrUtil.equalsIgnoreCase("create", entity.getStatus()), "该状态不允许核实");

        BeanUtil.copyProperties(form, entity,"patientCode"); //患者编号不能变
        entity.setStatus("done");
        int row = omicsCollectDao.update(entity);

        if(row>0){
            SamplePushForm pushForm = new SamplePushForm();
            String patientCode = form.getPatientCode();
            PatientEntity patient = patientDao.selectOneByPatientCode(patientCode);
            pushForm.setCaseid(form.getSampleNo());
            pushForm.setPatientName(patient.getPatientName());
            pushForm.setCheckitem(TestItemConverter.getConvertString(patient.getTestItem()));
            pushForm.setLabAddress("院内实验室");
            pushForm.setSubhospcode(DictUtil.getLabel(patient.getHospitalSite(),"hospital_site_dict"));
            pushForm.setInspectionMaterials(new MaterialsConverter().getConvertString(form.getMaterials()));
            this.pushToKhSys(pushForm);
        }

        return row;
    }

    @Override
    public int stop(OmicsCollectStopForm form) {
        OmicsCollectEntity entity = omicsCollectDao.getById(form.getId());
        Assert.isTrue(ObjUtil.isNotNull(entity), "数据不见了");
        Assert.isTrue(!StrUtil.equalsIgnoreCase("stop", entity.getStatus()), "该状态不允许终止");

        entity.setStatus("stop");
        entity.setStopReason(form.getStopReason());
        return omicsCollectDao.update(entity);
    }

    @Override
    public int pushToKhSys(SamplePushForm form) {
        try {
            form.setOrigin("EDC-组学采样信息");
            String url = khSysUrl+"/api/sample/push";
            String responseBody = HttpUtil.post(url, JSON.toJSONString(form));
            Result result = JSON.parseObject(responseBody, Result.class);
            if(result.getCode()!=200){
                throw new RuntimeException(result.getDescription());
            }
        }catch (Exception e){
            log.error("同步样本至kh-sys失败",e);
            try {
                MailUtil.sendHtml("jiangconghui@biokanghui.com","EDC同步样本至KH-SYS样本库系统失败","样本编号："+form.getCaseid(),null);
            }catch (Exception e1){
                log.error("推送样本至康惠样本库系统失败后，发送邮件通知姜聪辉也失败",e1);
            }
        }

        return 0;
    }

}
